package com.xgzit.xgzmall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xgz
 * @Date 2021-07-04 21:21
 */
@Configuration
public class MyRabbitMqConfig {

    /** 设置消息转换的 序列化机制为json **/
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /*@RabbitListener(queues = "stock.release.stock.queue")
    public void handle(Message message){

    }*/

    /** 创建库存交换机 **/
    @Bean
    public Exchange stockEventExchange(){
        return new TopicExchange("stock-event-exchange", true, false);
    }

    /** 创建普通队列 库存服务-释放-库存-队列 **/
    @Bean
    public Queue stockReleaseStockQueue(){
        return new Queue("stock.release.stock.queue", true, false, false);
    }

    /** 创建死信队列 库存服务-死信-队列 **/
    @Bean
    public Queue stockDelayQueue(){
        Map<String, Object> arguments = new HashMap<>(4);
        // 指定 死信路由
        arguments.put("x-dead-letter-exchange", "stock-event-exchange");
        // 指定 死信路由键
        arguments.put("x-dead-letter-routing-key", "stock.release");
        // 指定 消息过期时间  单位为毫秒 1000毫秒=1秒
        arguments.put("x-message-ttl", 180000);
        return new Queue("stock.delay.queue", true, false, false, arguments);
    }

    /** 库存解锁普通队列 与 交换机 绑定 **/
    @Bean
    public Binding stockReleaseBinding(){
        return new Binding("stock.release.stock.queue",
                Binding.DestinationType.QUEUE ,
                "stock-event-exchange",
                "stock.release.#",
                null);
    }
    /** 延时队列与 交换机的绑定关系 **/
    @Bean
    public Binding stockLockedBinding(){
        return new Binding("stock.delay.queue",
                Binding.DestinationType.QUEUE ,
                "stock-event-exchange",
                "stock.locked",
                null);
    }
}
